<template>
  <div class="upload-container">
    <!-- 学期选择 -->
    <div class="upload-hint">
      <el-input
        v-model="semester"
        placeholder="请输入学期（例如：2024-2025学年秋季学期）"
        @input="validateSemester"
      />
      <span v-if="semesterError" class="error">{{ semesterError }}</span>
    </div>

    <!-- 模板下载 -->
    <div class="upload-hint">
      <p>点击下载模板</p>
      <el-button type="primary" @click="handleDownloadExcel">下载示例模板</el-button>
    </div>

    <!-- 文件上传 -->
    <el-upload
      class="upload-demo"
      drag
      :http-request="customRequest"
      :limit="1"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传Excel文件，且不超过2MB</div>
    </el-upload>

    <!-- 上传进度显示 -->
    <div v-if="taskInfo.status === 'processing'" class="progress-container">
    <p>正在处理中...</p>
    <div class="progress-details">
      <!-- 使用 el-progress 的插槽来显示自定义文本 -->
      <el-progress
        :percentage="taskInfo.progress.percent"
        :stroke-width="20"
      >
        <span>{{ taskInfo.progress.current }}/{{ taskInfo.progress.total }}</span>
      </el-progress>
    </div>
  </div>

    <!-- 成功/失败提示 -->
    <div v-if="taskInfo.status === 'success'" class="result-container success">
      <p>导入成功！</p>
      <p>共导入 {{ taskInfo.result.imported }} 条数据</p>
    </div>

    <div v-if="taskInfo.status === 'failure'" class="result-container error">
      <p>导入失败，请检查文件内容</p>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onBeforeUnmount} from 'vue';
import { ElMessage } from 'element-plus';
import {formDataApi, jsonApi} from "@/global.js";
import * as Json from "postcss";
const semester = ref('');
const semesterError = ref('');
const taskInfo = reactive({
  status: null,
  result: null,
  progress: null
});
const timer = ref(null);

// 学期格式验证
const validateSemester = () => {
  const regex = /^[0-9]{4}-[0-9]{4}学年(春季|秋季)学期$/;
  if (!regex.test(semester.value)) {
    semesterError.value = '学期格式不正确，请输入如：2024-2025学年秋季学期';
  } else {
    semesterError.value = '';
  }
};

// 文件上传前验证
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件');
  }
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB');
  }
  return isExcel && isLt5M;
};

// 文件上传处理
const customRequest = async (options) => {
  const file = options.file;

  // 最终验证学期格式
  if (!semester.value || semesterError.value) {
    ElMessage.error('请正确输入学期信息');
    return;
  }

  const formData = new FormData();
  formData.append('excel_file', file);
  formData.append('semester', semester.value);

  try {
    const response = await formDataApi('/teachingarrangementmanagement/admins_course_createByWord/', formData);
    // 控制台打印
    const taskInfo = await  response.json();
    console.log(taskInfo);
    if (taskInfo['status'] === 'processing'){
       startPolling(taskInfo['task_id']);
    }
  } catch (error) {
    ElMessage.error('上传失败，请重试:'+error);
  }
};

// 开始轮询任务状态
const startPolling = (taskId) => {
  timer.value = setInterval(async () => {
    const data = { task_id: taskId };

    try {
      const res = await jsonApi('/taskStatus/', JSON.stringify(data));
      const res_data= await res.json();
      // 处理不同状态
      switch (res_data['state']) {
        case 'PROGRESS':
          taskInfo.status = 'processing';
          taskInfo.progress = res_data['progress'];
          break;
        case 'SUCCESS':
          clearInterval(timer.value);
          taskInfo.status = 'success';
          taskInfo.result = res_data['result'];
          break;
        case 'FAILURE':
          clearInterval(timer.value);
          taskInfo.status = 'failure';
          break;
      }
    } catch (error) {
      clearInterval(timer.value);
      ElMessage.error('获取任务状态失败');
    }
  }, 3000); // 每3秒轮询一次
};

// 模板下载方法
const handleDownloadExcel = async () => {
  try {
    const requestData = {
      file_url: "FileTemplate/2024-2025学年春季学期.xlsx"
    };

    // 确保 jsonApi 内部 Axios 配置了 responseType: 'blob'
    const response = await jsonApi('/file/download/', JSON.stringify(requestData));

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // 创建一个blob对象，它表示了一段不可变的原始数据
    const blob = await response.blob();

    // 创建一个链接元素，用于下载文件
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;

    // 设置下载的文件名，确保服务器在响应头中设置了正确的文件名
    let fileName = 'downloaded.xlsx'; // 默认文件名
    const contentDisposition = response.headers.get('content-disposition');
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename="?([^"]*)"?$/);
      if (fileNameMatch) {
        fileName = fileNameMatch[1]; // 使用从响应头中提取的文件名
      }
    }

    a.download = fileName;

    // 触发下载
    document.body.appendChild(a);
    a.click();

    // 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success('模板下载成功');
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error('下载模板失败：' + (error.message || '未知错误'));
  }
};
// 善后处理
onBeforeUnmount(() => {
  clearInterval(timer.value);
});
</script>

<style scoped>
.upload-container {
  max-width: 600px;
  margin: 20px auto;
}

.upload-hint {
  margin-bottom: 20px;
}

.error {
  color: red;
}

.progress-container {
  margin-top: 20px;
}

.result-container {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid;
  border-radius: 4px;
}

.result-container.error {
  border-color: red;
  background-color: #f8d7da;
}
</style>